<template>
  <view>
    <!-- pages/post_thread/post_thread.wxml -->
    <view class="container">
      <form @submit.stop.prevent="formSubmit">
        <!-- <view class='classTypeView' wx:if="{{fid!=2&&classTypeList && !isreply && !isevaluate}}">
<picker class='classType' name="classType" mode="selector" range="{{classTypeList}}" range-key='name' bindchange="classTypeChange">
<text decode="{{true}}">{{classTypeList[classIndex].name?classTypeList[classIndex].name:'课程分类'}}</text>
</picker>
</view> -->
        <!--  -->
        <view class="classTypeView" v-if="!isreply && !isevaluate">
          <picker class="easyType" name="classType" mode="selector" :range="classTypeList" range-key="name"
                  @change="classTypeChange" v-if="classTypeList.length > 0">
            <text class="text-deal" :decode="true">
              {{ classTypeList[classIndex].name ? classTypeList[classIndex].name : '选分类' }}
            </text>
          </picker>
          <input class="easyInput" name="subject" placeholder="标题"/>
        </view>

        <textarea
            v-if="!fullScreen"
            class="weui-input detailText"
            name="message"
            :placeholder="detailplaceholder"
            :value="detaiContent"
            @blur="detailFinish"
            :focus="isText"
            maxlength="-1"
        />
        <view class="weui-input detailText" v-if="fullScreen" @tap="detailBegin">
          {{ detaiContent ? detaiContent : detailplaceholder }}
        </view>

        <view class="attachmentContain" v-if="!isevaluate">
          <view class="audio-playView" v-if="recording">
            <image mode="widthFix" :src="minImgDoc + 'record_close.png'" class="record-close" @tap="clear"></image>
            <view class="record-time">{{ formatedRecordTime }}</view>
            <image class="record-icon" :src="minImgDoc + 'record_icon.png'" @tap="parse" :data-type="is_parse"></image>
            <view class="record-finish" @tap="stopRecord">完成</view>
          </view>

          <view class="playViewContain" v-if="audio.aid">
            <view class="audio-playView">
              <image
                  mode="widthFix"
                  :src="is_play ? minImgDoc + 'audio_play.png' : minImgDoc + 'audio_paused.png'"
                  class="audio-icon audio-play"
                  @tap="audio_play"
              ></image>
              <view class="control-process">
                <text class="current-process">
                  <block v-if="current_process.length > 0">
                    {{ current_process }}
                  </block>
                  <block v-else>00:00</block>
                </text>
                <slider
                    class="slider"
                    @change="hanle_slider_change"
                    @touchstart="handle_slider_move_start"
                    @touchend="handle_slider_move_end"
                    min="0"
                    block-size="12"
                    block-color="#6199fd"
                    :max="slider_max"
                    activeColor="#5abf39"
                    backgroundColor="rgb(153,153,153,0.4)"
                    :value="slider_value"
                />
                <text class="total-process">
                  <block v-if="total_process.length > 0">
                    {{ total_process }}
                  </block>
                  <block v-else>00:00</block>
                </text>
              </view>
            </view>
            <image class="deleteA audioDele" :src="minImgDoc + 'att_delete.png'" :id="audio.aid"
                   @tap="deleteAudio"></image>
          </view>

          <view class="uploader__files">
            <block v-for="(image, index) in imageList" :key="image.aid">
              <view class="uploader__file" :id="image.aid">
                <image class="uploader__img" :src="image.src" :data-src="image.src" @tap="previewImage"></image>
                <image class="deleteA" :src="minImgDoc + 'att_delete.png'" :id="image.aid" @tap="deleteImage"></image>
              </view>
            </block>
            <view class="uploader_videoContain" v-if="video.aid">
              <view class="uploader__file" :id="image.aid">
                <video
                    id="myVideo"
                    class="uploader__video uploader__input"
                    :controls="false"
                    :show-fullscreen-btn="false"
                    @play="playVideo"
                    @fullscreenchange="fullScreenChange"
                    :src="video.src"
                ></video>
                <image class="deleteA" :src="minImgDoc + 'att_delete.png'" :id="video.aid" @tap="deleteVideo"></image>
              </view>
            </view>
            <image class="uploader__input" v-if="imageList.length !== 9" :src="minImgDoc + 'post_addimage.png'"
                   @tap="chooseImage"></image>
            <image class="uploader__input" :src="minImgDoc + 'post_addaudio.png'" @tap="chooseAudio"></image>
            <image class="uploader__input" :src="minImgDoc + 'post_addvideo.png'" @tap="chooseVideo"></image>
          </view>
        </view>
        <button class="postBtn" :disabled="postLock" type="primary" formType="submit">发布</button>
      </form>
    </view>

    <secode ref="secode" :codeShow="codeShow" @secodeSubmit="secodeSubmit" id="secode"></secode>
  </view>
</template>

<script>

const postThreadUrl = require('../../config').postThreadUrl;

const postReplyUrl = require('../../config').postReplyUrl;

const postInfoUrl = require('../../config').postInfoUrl;

const uploadFileUrl = require('../../config').uploadFileUrl;

const replyWorkUrl = require('../../config').replyWorkUrl;

const minImgDoc = require('../../config').minImgDoc;

const util = require('../../utils/util.js');

const datacheck = require('../../utils/datacheck.js');

var event = require('../../utils/event.js');


const app = getApp();
var recordTimeInterval; // 附件分类

var fileCatalog = {
  image: 0,
  audio: 1,
  video: 2
};
export default {
  data() {
    return {
      minImgDoc: minImgDoc,
      classIndex: 0,
      fid: '',
      tid: '',
      is_quan: false,
      uploadhash: '',
      classTypeList: null,
      imageList: [],
      recordTime: 0,
      recording: false,
      detaiContent: '',
      isreply: false,
      is_fenl: false,
      detailplaceholder: '详细内容',
      audioPrepareUrl: '',
      postLock: false,
      is_parse: 1,
      threads: '',
      isevaluate: '',
      pid: '',
      isText: false,
      hasRecord: false,
      current_process: '',
      slider_value: '',
      total_process: '',
      slider_max: '',
      fullScreen: false,
      formatedRecordTime: '',

      audio: {
        aid: ''
      },

      video: {
        src: '',
        aid: ''
      },

      status: 0,
      is_play: false,
      is_ended: false,
      is_moving_slider: false,
      postDic: '',
      codeShow: false,

      image: {
        aid: '',
        src: ''
      }
    };
  },
  onReady() {
    this.videoContext = uni.createVideoContext('myVideo');
  },
  mounted() {
    // console.log(this.$refs.secode)
    this.$refs.secode.requestCode('post');
  },
  onHide: function () {
    if (this.recording) {
      this.recording = false;
      this.recordTime = 0;
      this.stopRecord();
    }
  },
  onUnload: function () {
    if (this.recording) {
      this.recording = false;
      this.recordTime = 0;
      this.stopRecord();
      this.recorderManager = null;
    }

    uni.setKeepScreenOn({
      keepScreenOn: false
    });
  },


  onLoad: function (options) {
    // secode

    var fid = options.fid;
    let isreply = options.isreply;
    let isevaluate = options.isevaluate;
    var is_quan = options.is_quan ? options.is_quan : false;

    if (is_quan) {
      this.detailplaceholder = '话题';
    }

    if (isreply || isevaluate) {
      let pages = getCurrentPages(); //获取当前页面

      let prevPage = pages[pages.length - 2]; //获取上个页面
//data换成$data
      let threads = prevPage.$data.thread;
      var tid = '';

      if (threads) {
        this.threads = threads;
        fid = threads.fid;
        tid = threads.tid;
      }

      if (options.tid) {
        tid = options.tid;
      }

      if (isevaluate) {
        this.isevaluate = isevaluate;
        this.pid = options.pid;
      } else {
        if (isreply) {
          this.isreply = isreply;
        }
      }

      console.log(tid);
      this.tid = tid;
      this.detailplaceholder = '评论（不少于10个字）';

      if (this.isreply || this.isevaluate) {
        uni.setNavigationBarTitle({
          title: '回复'
        });
      }

      if (options.type) {
        if (options.type == 'text') {
          this.isText = true;
        } else {
          if (options.type == 'image') {
            setTimeout(function () {
              this.chooseImage();
            }, 300);
          } else {
            if (options.type == 'audio') {
              this.chooseAudio();
            } else {
              if (options.type == 'video') {
                setTimeout(function () {
                  this.chooseVideo();
                }, 300);
              }
            }
          }
        }
      }
    }

    this.fid = fid;
    this.is_quan = is_quan;

    if (this.isreply || this.isevaluate) {
      var navtitle = '回复';
      uni.setNavigationBarTitle({
        title: navtitle
      });
    }

    this.checkPost(); // 语音

    this.recorderManager = uni.getRecorderManager();
    this.recorderManager.onError(function (res) {
      var errMsg = res.errMsg;

      if (errMsg.indexOf('auth deny') != -1) {
        // errMsg = "没有访问麦克风的权限"
        // wx.showToast({
        //   title: errMsg,
        //   icon: 'none'
        // })
      }
    });
    this.recorderManager.onStop(function (res) {
      this.hasRecord = true;
      uni.setKeepScreenOn({
        keepScreenOn: false
      });
      clearInterval(recordTimeInterval);
      var recordTime = Math.floor(res.duration / 1000);
      this.recordTime = recordTime;
      console.log('this.recording', this.recording);

      if (this.recording) {
        this.audioPrepareUrl = res.tempFilePath;
        console.log('res.tempFilePath', res.tempFilePath);
        this.uploadFile(res.tempFilePath, fileCatalog.audio);
      }
    });
    this.recorderManager.onPause(function (res) {
    });
    this.recorderManager.onResume(function (res) {
    });
    this.innerAudioContext = uni.createInnerAudioContext();
    this.innerAudioContext.onTimeUpdate(() => {
      if (!this.is_moving_slider) {
        // 播放中
        this.current_process = util.formatTime(this.innerAudioContext.currentTime)
        this.total_process = util.formatTime(this.innerAudioContext.duration)
        this.slider_max = Math.floor(this.innerAudioContext.duration)

      }

      if (this.innerAudioContext.currentTime >= this.recordTime) {
        this.stopVoice();
      }
    });
  },
  methods: {
    detailBegin() {
      this.fullScreen = false;
      this.isText = true;
    },

    detailFinish(e) {
      this.detaiContent = e.detail.value;
    },

    playVideo() {
      this.videoContext.play();
      this.videoContext.requestFullScreen();
    },

    fullScreenChange(e) {
      console.log(e.detail);
      this.fullScreen = e.detail.fullScreen;
    },

    checkPost() {
      var url = postInfoUrl + '&submodule=checkpost&version=5';
      app.globalData.apimanager
          .getRequest(url, {
            fid: this.fid
          })
          .then((res) => {
            if (res.Variables.allowperm) {
              this.uploadhash = res.Variables.allowperm.uploadhash;
            }

            var types = res.Variables.threadtypes.types;
            var array = [];

            for (let key in types) {
              let value = types[key];
              let data = {
                typeid: key,
                name: value
              };
              array.push(data);
            }

            types = array;
            this.classTypeList = types;
          })
          .catch((res) => {
          });
    },

    secodeSubmit(e) {
      this.postDic['sechash'] = e.detail.sechash;
      this.postDic['seccodeverify'] = e.detail.seccodeverify;
      this.postThread();
    },

    parse: function (e) {
      if (e.currentTarget.dataset.type == 1) {
        this.recorderManager.pause();
        clearInterval(recordTimeInterval);
        this.is_parse = 2;
      } else {
        this.recorderManager.resume();
        recordTimeInterval = setInterval(function () {
          const recordTime = (this.recordTime += 1);
          this.setData({
            formatedRecordTime: util.formatTime(this.recordTime),
            recordTime
          });
        }, 1000);
        this.is_parse = 1;
      }
    },

    classTypeChange(e) {
      var classIndex = e.detail.value;
      console.log(classIndex);
      this.classIndex = classIndex;
    },

    chooseImage() {
      if (this.imageList.length == 9) {
        uni.showToast({
          title: '最多上传9张图片',
          icon: 'none'
        });
        return;
      }

      uni.chooseImage({
        count: 9 - this.imageList.length,

        success(res) {
          console.log(res);

          for (let key in res.tempFilePaths) {
            let imageSrc = res.tempFilePaths[key];
            this.uploadFile(imageSrc, fileCatalog.image);
          }
        }
      });
    },

    uploadFile(uploadSrc, type) {
      var uploadUrl = uploadFileUrl + '&fid=' + this.fid;
      let uploadhash = this.uploadhash;
      let uid = app.globalData.uid;
      let postDic = {
        hash: uploadhash,
        uid: uid
      };
      uni.showLoading({
        title: '上传附件',
        icon: 'loading'
      });
      console.log(postDic);
      app.globalData.apimanager
          .uploadFile(uploadUrl, uploadSrc, 'Filedata', postDic)
          .then((res) => {
            uni.hideLoading();
            var result = datacheck.uploadStatusCheck(res);

            if (result.success) {
              uni.showToast({
                title: '上传成功',
                icon: 'success',
                duration: app.globalData.duration
              });
              let aid = result.data;

              if (type == fileCatalog.image) {
                var imageList = this.imageList;
                let imgObj = {
                  aid: aid,
                  src: uploadSrc
                };
                imageList.push(imgObj);
                this.imageList = imageList;
              } else {
                if (type == fileCatalog.audio) {
                  this.audioPrepareUrl = '';
                  var data = {
                    aid: aid,
                    src: uploadSrc
                  };
                  let recordTime = this.recordTime;
                  this.audio = data
                  this.slider_max = Math.floor(recordTime)
                  this.recording = false

                } else {
                  if (type == fileCatalog.video) {
                    var data = {
                      aid: aid,
                      src: uploadSrc
                    };
                    this.video = data;
                  }
                }
              }
            } else {
              uni.showModal({
                content: result.data,
                showCancel: false,
                confirmText: '确定'
              });
            }
          })
          .catch((res) => {
            console.log(res);
            uni.hideLoading();
            uni.showModal({
              content: '上传失败',
              showCancel: false,
              confirmText: '确定'
            });
          });
    },

    previewImage(e) {
      const current = e.target.dataset.src;
      var imageSrcArray = [];

      for (let i = 0; i < this.imageList.length; i++) {
        let item = this.imageList[i];
        imageSrcArray.push(item.src);
      }

      uni.previewImage({
        current,
        urls: imageSrcArray
      });
    },

    chooseAudio() {
      // if (this.audio) {
      //   wx.showToast({
      //     title: '最多上传一个语音',
      //     icon: 'none'
      //   })
      //   return
      // }
      if (this.recording) {
        return;
      }

      this.startRecord();
    },

    chooseVideo() {
      uni.chooseVideo({
        camera: 'back',
        maxDuration: 60,

        success(res) {
          this.uploadFile(res.tempFilePath, fileCatalog.video);
        }
      });
    },

    startRecord() {
      uni.authorize({
        scope: 'scope.record',

        success() {
          console.log('录音授权成功'); //第一次成功授权后 状态切换为2

          this.status = 2; // 用户已经同意小程序使用录音功能，后续调用 this.recordStart 接口不会弹窗询问

          this.recordStartNow();
        },

        fail() {
          uni.showModal({
            title: '提示',
            content: '您未授权录音，功能将无法使用',
            showCancel: true,
            confirmText: '授权',
            confirmColor: '#52a2d8',
            success: function (res) {
              if (res.confirm) {
                //确认则打开设置页面（重点）
                uni.openSetting({
                  success: (res) => {
                    console.log(res.authSetting);

                    if (!res.authSetting['scope.record']) {
                      //未设置录音授权
                      console.log('未设置录音授权');
                      uni.showModal({
                        title: '提示',
                        content: '您未授权录音，功能将无法使用',
                        showCancel: false,
                        success: function (res) {
                        }
                      });
                    } else {
                      //第二次才成功授权
                      this.status = 2;
                      this.recordStartNow();
                    }
                  },
                  fail: function () {
                    console.log('授权设置录音失败');
                  }
                });
              } else {
                if (res.cancel) {
                  console.log('cancel');
                }
              }
            },
            fail: function () {
              console.log('openfail');
            }
          });
        }
      });
    },

    recordStartNow() {
      clearInterval(recordTimeInterval);
      this.setData({
        recording: true,
        recordTime: 0,
        formatedRecordTime: '00:00',
        audioPrepareUrl: ''
      });
      uni.setKeepScreenOn({
        keepScreenOn: true
      });
      recordTimeInterval = setInterval(function () {
        const recordTime = (this.recordTime += 1);
        this.setData({
          formatedRecordTime: util.formatTime(this.recordTime),
          recordTime
        });
      }, 1000);
      this.recorderManager.start({
        format: 'mp3',
        duration: 180000
      });
    },

    stopRecord() {
      clearInterval(recordTimeInterval);
      this.recorderManager.stop();

      if (this.audioPrepareUrl) {
        this.uploadFile(this.audioPrepareUrl, fileCatalog.audio);
      }
    },

    // 点击播放暂停
    audio_play: function () {
      if (this.is_play) {
        this.is_play = false;
        console.log('暂停');
        this.innerAudioContext.pause();
      } else {
        if (!this.is_play && this.is_ended) {
          this.playVoice();
          this.is_play = true;
          this.is_ended = false;
        } else {
          if (!this.is_play) {
            console.log('即将播放');
            this.is_play = true;
            this.playVoice();
          }
        }
      }
    },

    // 拖动进度条，到指定位置
    hanle_slider_change(e) {
      const position = e.detail.value;
      this.seekCurrentAudio(position);
    },

    // 拖动进度条控件
    seekCurrentAudio(position) {
      this.innerAudioContext.seek(position)
      this.current_process = util.formatTime(position)
    },

// 进度条滑动
    handle_slider_move_start() {
      this.is_moving_slider = true;
    }
    ,

    handle_slider_move_end() {
      this.is_moving_slider = false;
    }
    ,

    playVoice() {
      var src = this.audio.src;

      if (src == '') {
        return;
      }

      this.innerAudioContext.src = src;
      this.innerAudioContext.play();
    }
    ,

    stopVoice() {
      this.current_process = util.formatTime(0)
      this.is_play = false
      this.innerAudioContext.stop();
    },

    clear() {
      this.setData({
        is_play: false,
        hasRecord: false,
        recording: false,
        audio: null,
        formatedRecordTime: util.formatTime(0),
        recordTime: 0
      });
      this.stopRecord();
    }
    ,

    deleteVideo(e) {
      var aid = e.currentTarget.id;
      console.log(aid);
      this.video = null;
    }
    ,

    deleteImage(e) {
      var aid = e.currentTarget.id;
      var imageList = this.imageList;
      var index;

      for (let i = 0; i < imageList.length; i++) {
        let data = imageList[i];

        if (data.aid == aid) {
          index = i;
        }
      }

      imageList.splice(index, 1);
      this.imageList = imageList;
      console.log(aid);
    }
    ,

    deleteAudio(e) {
      var aid = e.currentTarget.id;
      this.audio = null;
    }
    ,

    formSubmit(e) {
      if (datacheck.isEmojiCharacter(e.detail.value.message) || datacheck.isEmojiCharacter(e.detail.value.subject)) {
        uni.showToast({
          title: '不能使用emoji表情',
          icon: 'none'
        });
        return;
      }

      var postDic = {
        formhash: app.globalData.formhash
      };

      if (e.detail.value.message) {
        if (e.detail.value.message.length > 0) {
          let msg = e.detail.value.message;
          postDic['message'] = msg;

          if (!this.isreply && !this.isevaluate) {
            let length = msg.length < 40 ? msg.length : 40;
            postDic['subject'] = msg.substr(0, length);
          }
        }
      } else {
        let msg = this.detaiContent;
        postDic['message'] = msg;

        if (!this.isreply && !this.isevaluate) {
          let length = msg.length < 40 ? msg.length : 40;
          postDic['subject'] = msg.substr(0, length);
        }
      }

      if (e.detail.value.subject) {
        postDic['subject'] = e.detail.value.subject;
      } else {
        if (!(this.isreply || this.isevaluate)) {
          uni.showToast({
            title: '请输入标题',
            icon: 'none'
          });
          return;
        }
      }

      if (this.imageList.length > 0) {
        for (let i = 0; i < this.imageList.length; i++) {
          let imgObj = this.imageList[i];
          let aid = imgObj['aid'];
          let attachKey = 'attachnew[' + aid + '][description]';
          postDic[attachKey] = '';
        }
      }

      if (this.audio) {
        let attachKey = 'attachnew[' + this.audio.aid + '][description]';
        postDic[attachKey] = this.recordTime;
      }

      if (this.video) {
        let attachKey = 'attachnew[' + this.video.aid + '][description]';
        postDic[attachKey] = '';
      }

      if (this.classTypeList && this.classTypeList.length > 0 && !this.isreply && !this.isevaluate) {
        if (e.detail.value.classType.length <= 0) {
          e.detail.value.classType = 0;
        }

        let typeIndex = parseInt(e.detail.value.classType);
        let classObj = this.classTypeList[typeIndex];
        postDic['typeid'] = classObj.typeid;
      }

      this.postDic = postDic;

      if (this.$refs.secode.haveCode()) {
        this.codeShow = true;
        this.fullScreen = true;
        return;
      }

      this.postThread();
    }
    ,

    postThread() {
      this.postLock = true;
      var isRefresh = false;
      var url = postThreadUrl;

      if (this.isreply) {
        // 交作业
        url = postReplyUrl + '&fid=' + this.fid + '&tid=' + this.tid;

        if (this.is_quan) {
          isRefresh = true;
        }
      } else {
        if (this.isevaluate) {
          // 回复作业
          url = replyWorkUrl + '&tid=' + this.tid + '&pid=' + this.pid;
        } else {
          // 发帖 发布作业
          isRefresh = true;
          url = url + '&fid=' + this.fid;
        }
      }

      uni.showLoading({
        title: '发布中...',
        icon: 'loading'
      });
      var postDic = this.postDic;
      app.globalData.apimanager
          .postRequest(url, postDic)
          .then((res) => {
            uni.hideLoading();

            if (res.Message.messageval.indexOf('succeed') != -1 || res.Message.messageval.indexOf('success') != -1) {
              if (isRefresh && this.is_quan) {
                // 发作业题目
                if (this.isreply) {
                  event.emit('indexChanged', {
                    name: 'workRefresh',
                    reply: true,
                    tid: this.tid
                  });
                } else {
                  event.emit('indexChanged', {
                    name: 'workRefresh'
                  });
                }
              } else {
                // 交作业
                var pages = getCurrentPages();
                var prevPage = pages[pages.length - 2]; //上一个页面

                prevPage.refreshRequest();
              }

              if (res.Message.messagestr.indexOf('审核') != -1) {
                setTimeout(function () {
                  uni.navigateBack();
                }, 2000);
              } else {
                uni.navigateBack();
              }
            } else {
              this.postLock = false;
            }

            uni.showToast({
              title: res.Message.messagestr,
              icon: 'none',
              mask: true,
              duration: app.globalData.duration
            });
          })
          .catch((res) => {
            console.log(res);
            uni.hideLoading();
            this.postLock = false;
            uni.showToast({
              title: '服务器繁忙，请稍后再试！',
              icon: 'none'
            });
          });
    }
  }
}
;
</script>
<style>
@import './post_thread.css';
</style>
